<?php
class CMlm
{
	public $config = array();
	
	public function getConfig()
	{		
		return $this->config;
	}
	
	public function __construct()
	{
		$file = MY_ROOT . '/php_config/mlm.ini';
		$arr = parse_ini_file($file, 1);
		$this->config = $arr;
	}
	
	public function bindMemberToInvitor($uid, $invitorId)
	{
		$mlmMember = new CMlmmember();
		$row = $mlmMember->fetchRow(array('uid = ?'=>$invitorId));
		if (!$row && $invitorId) {
			$mlmMember->insert(array('uid'=>$invitorId, 'invitor_uid'=>0, 'add_time'=>time()));
		}
		return $mlmMember->insert(array('uid'=>$uid, 'invitor_uid'=>$invitorId, 'add_time'=>time()));
	}
	
	public function dispatchRebate($orderid)
	{
		$order = new COrder();
		$orderDetail = $order->fetchRow(array('orderid = ?'=>$orderid));
		$mlmOrderRebateLog = new CMlmorderrebatelog();
		$row = $mlmOrderRebateLog->fetchRow(array('orderid = ?'=>$orderid));
		if ($row) {
			return false;
		}
		//用户自己的
		if (!$this->isMlmUser($orderDetail->uid)) {
			$mlmMember = new CMlmmember();
			$mlmMember->insert(array('uid'=>$orderDetail->uid, 'invitor_uid'=>0, 'add_time'=>time()));
		}
		$this->doRebate($orderDetail->uid, $orderDetail->money * 0.03, 3, $orderid);	
		$data=array(
    				'from_uid'=>1,
    				'to_uid'=>$orderDetail->uid,
    				'add_time'=>time(),
    				'subject'=>'Your have earned $'.number_format($orderDetail->money * 0.03,2),
    				'content'=>'You have earned $'.number_format($orderDetail->money * 0.03,2).' from your referee. Please <a href="http://www.bestcheapjerseydeal.com/adminb-mlm">Check my referee account here.</a> ',
    				'has_read'=>0,
    				'flid'=>1,
    			   );
    	$pm = new CPm();
    	$pm->createPm($data);
		//
		if (!$this->isMlmUser($orderDetail->uid)) {
			return false;
		}
		$tmpUid = $orderDetail->uid;		
		$mlmOrderRebateLog->insert(array('orderid'=>$orderid, 'add_time'=>time()));	
		for ($i =1; $i <= $this->config['rebate']['level']; $i++) {			
			$tmpUid = $this->getMemberInvitorUid($tmpUid);
			if ($tmpUid == 0) {
				break;
			}
			$amount = 0;
			$amount = $orderDetail->money * $this->config['rebate']['rebate_percent_' . $i] / 100;
			
			$this->doRebate($tmpUid, $amount, $this->config['rebate']['rebate_percent_' . $i], $orderid);		

			$data=array(
    				'from_uid'=>1,
    				'to_uid'=>$tmpUid,
    				'add_time'=>time(),
    				'subject'=>'Your have earned $'.$amount,
    				'content'=>'You have earned $'.$amount.' from your referee. Please <a href="http://www.bestcheapjerseydeal.com/adminb-mlm">Check my referee account here.</a> ',
    				'has_read'=>0,
    				'flid'=>1,
    			   );
	    	$pm = new CPm();
	    	$pm->createPm($data);
		}		
		return;
	}
	
	public function doRebate($uid, $amount, $percent, $orderid)
	{
		$mlmRebate = new CMlmrebate();
		$mlmRebate->insert(array('uid'=>$uid, 'amount'=>$amount, 'rebate_percent'=>$percent, 'orderid'=>$orderid, 'add_time'=>time()));
		
		$sql = 'update zcshop_mlm_member set cash=cash+' . $amount . ', update_time=' . time() . ' where uid=' . $uid;
	
		$db = $mlmRebate->getAdapter();
		$db->query($sql);
	}
	
	public function getMemberInvitorUid($uid)
	{
		$mlmMember = new CMlmmember();
		$row = $mlmMember->fetchRow(array('uid = ?'=>$uid));
		if (!$row) {
			return 0;
		}
		return $row->invitor_uid;
	}
	
	public function cash($uid, $cash, $paypal)
	{
		$mlmMember = new CMlmmember();
		$row = $mlmMember->fetchRow(array('uid = ?'=>$uid));
		if (!$row) {
			return false;
		}
		
		$inProcess = $this->getInProcessCash($uid);		
		if ($row->cash - $inProcess < $cash) {
			return false;
		}

		$db = $mlmMember->getAdapter();
		$mlmCashLog = new CMlmcashlog();
		$db->beginTransaction();
		try {
			$mlmCashLog->insert(array('cash'=>$cash, 'uid'=>$uid, 'paypal'=>$paypal, 'add_time'=>time()));
			$db->commit();
			return true;
		} catch (Exception $e) {
			$db->rollback();
			return false;
		}
	}
	
	public function exchange($uid, $cash)
	{
		$mlmMember = new CMlmmember();
		$row = $mlmMember->fetchRow(array('uid = ?'=>$uid));
		if (!$row) {
			return false;
		}
		
		$inProcess = $this->getInProcessCash($uid);		
		if ($row->cash - $inProcess < $cash) {
			return false;
		}

		$db = $mlmMember->getAdapter();
		$mlmExchangeLog = new CMlmexchangelog();
		$db->beginTransaction();
		try {
			$config = new CConfig();
	    	$score = $config->getByName('ORDER_SCORE');
	    	$scoreArr = explode('|', $score->data);
	    	$integral = $scoreArr[0] * $cash;
	    	$member = new CMember();
	    	$member->updateIntegral($integral, $uid, 1);
			$mlmExchangeLog->insert(array('cash'=>$cash, 'uid'=>$uid, 'add_time'=>time()));
			$db->query('update zcshop_mlm_member set cash=cash-' . $cash . ', update_time=' . time() . ' where uid = ' . $uid);
			$db->commit();
			return true;
		} catch (Exception $e) {
			$db->rollback();
			return false;
		}
	}
	
	public function doCash($logId, $statu)
	{
		$mlmCashLog = new CMlmcashlog();
		$row = $mlmCashLog->fetchRow(array('log_id = ?'=>$logId));
		if (!$row) {
			return false;
		}
		$db = $mlmCashLog->getAdapter();
		$db->beginTransaction();
		try {
			$mlmCashLog->update(array('statu'=>$statu, 'update_time'=>time()), 'log_id=' . $logId);
			if ($statu == 1) { //减掉相应金额
				$sql = 'update zcshop_mlm_member set cash=cash-' . $row->cash . ', update_time=' . time() . ' where uid = ' . $row->uid;
				
				$db->query($sql);
			}
			$db->commit();
			return true;
		} catch (Exception $e) {
			$db->rollback();
			return false;
		}
	}
	
	public function getInProcessCash($uid = 0)
	{
		$mlmCashLog = new CMlmcashlog();
		$sql = 'select sum(cash) as total from zcshop_mlm_cash_log where statu=0';
		if ($uid) {
			$sql .= ' and uid=' . $uid;
		}
		$db = $mlmCashLog->getAdapter();
		$row = $db->fetchAll($sql);
		if ($row[0]['total']) {
			return $row[0]['total'];
		}
		return 0;
	}
	
	public function getSuccessCash($uid = 0)
	{
		$mlmCashLog = new CMlmcashlog();
		$sql = 'select sum(cash) as total from zcshop_mlm_cash_log where statu=1';
		if ($uid) {
			$sql .= ' and uid=' . $uid;
		}
		$db = $mlmCashLog->getAdapter();
		$row = $db->fetchAll($sql);		
		if ($row[0]['total']) {
			return $row[0]['total'];
		}
		return 0;
	}
	
	public function getRefuseCash($uid = 0)
	{
		$mlmCashLog = new CMlmcashlog();
		$sql = 'select sum(cash) as total from zcshop_mlm_cash_log where statu=2';
		if ($uid) {
			$sql .= ' and uid = ' . $uid;
		}
		$db = $mlmCashLog->getAdapter();
		$row = $db->fetchAll($sql);
		if ($row[0]['total']) {
			return $row[0]['total'];
		}
		return 0;
	}
	
	public function getAllCash($uid)
	{
		$mlmMember = new CMlmmember();
		$row = $mlmMember->fetchRow(array('uid = ?'=>$uid));
		if ($row) {
			return $row->cash;
		}
		return 0;
	}
	
	public function isMlmUserFirstBuy($uid)
	{
		if (!$this->isMlmUser($uid)) {
			return false;
		}
		$order = new COrder();
		$orders = $order->fetchAll(array('uid = ?'=>$uid));
		if (count($orders) > 0) {
			return false;
		}	
		return true;
	}
	
	public function isMlmUser($uid)
	{
		$mlmMember = new CMlmmember();
		$row = $mlmMember->fetchRow(array('uid = ?'=>$uid));
		if ($row) {
			return $row;
		}
		return 0;
	}

	public function calcRebate($level1, $level2, $level3, $amount)
	{
		return $level1 * $amount * $this->config['rebate']['rebate_percent_1'] / 100 + $level1 * $level2 * $amount * $this->config['rebate']['rebate_percent_2'] / 100  + $level1 * $level2 * $level3 * $amount * $this->config['rebate']['rebate_percent_3'] / 100;
	}
	
	private function genInviteCode($uid)
	{
		return ($uid + 2013) * 15;
	}
	
	public function memberInviteCode($uid)
	{
		$mlmInviteCode = new CMlminvitecode();
		$row = $mlmInviteCode->fetchRow(array('uid = ?'=>$uid));
		if ($row) {
			return $row->invite_code;
		}
		$code = $this->genInviteCode($uid);
		$mlmInviteCode->insert(array('uid'=>$uid, 'invite_code'=>$code, 'add_time'=>time()));
		return $code;
	}
	
	public function getMemberByInviteCode($code)
	{
		$mlmInviteCode = new CMlminvitecode();
		$row = $mlmInviteCode->fetchRow(array('invite_code = ?'=>$code));
		
		if ($row) {
			return $row->uid;
		}
		return 0;
	}
	
	public static function getInviteCode()
	{
		$session = new Zend_Session_Namespace('member');
        if (isset($session->inviteCode)) {
        	return $session->inviteCode;
        }
        return 0;
	}
	
	public function hasSuccessBuy($uid)
	{
		if($uid == 9803 || $uid == 9804 || $uid == 9805 || $uid == 9806 || $uid == 9807){
			return true;
		}
		$order = new COrder();
		$orders = $order->fetchAll(array('uid = ?'=>$uid, 'flid <> ?'=>1, 'flid <> ?'=>6, 'flid <> ?'=>7, 'flid <> ?'=>8));
		if (count($orders) > 0) {
			return true;
		}	
		return false;
	}
	
	public function getNextUid($uid)
	{
		$mlmMember = new CMlmmember();
		$sql = 'select uid from zcshop_mlm_member where invitor_uid=' . $uid;
		$db = $mlmMember->getAdapter();
		$result = $db->fetchAll($sql);
		if (empty($result)) {
			return array();
		}
		$reutrn = array();
		foreach ($result as $v) {
			$return[] = $v['uid'];
		}
		return $return;
	}
	
	public function getLevel1Uid($uid)
	{
		return $this->getNextUid($uid);
	}
	
	public function getLevel2Uid($uid)
	{
		$uids = $this->getLevel1Uid($uid);
		$return = array();
		foreach ($uids as $v) {
			$tmp = $this->getNextUid($v);
			foreach ($tmp as $_v) {
				$return[] = $_v;
			}
		}
		return $return;
	}
	
	public function getLevel3Uid($uid)
	{
		$uids = $this->getLevel2Uid($uid);
		$return = array();
		foreach ($uids as $v) {
			$tmp = $this->getNextUid($v);
			foreach ($tmp as $_v) {
				$return[] = $_v;
			}
		}
		return $return;
	}
	
	public function getOrderAmountByUid($uids)
	{
		$uid = implode(',', $uids);
		if (empty($uid)) {
			return 0;
		}
		$sql = 'select sum(money) as total from zcshop_orders where uid in (' . $uid . ') and flid=9';
		$mlmMember = new CMlmmember();		
		$db = $mlmMember->getAdapter();
		$result = $db->fetchAll($sql);
		if ($result[0]['total']) {
			return $result[0]['total'];
		}
		return 0;
	}
}